package com.lz.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.common.core.domain.entity.SysUser;
import com.lz.common.utils.DateUtils;
import com.lz.common.utils.SecurityUtils;
import com.lz.common.utils.StringUtils;
import com.lz.common.utils.file.FileUtils;
import com.lz.manage.mapper.FileInfoMapper;
import com.lz.manage.model.domain.FileInfo;
import com.lz.manage.model.domain.FolderInfo;
import com.lz.manage.model.domain.TagInfo;
import com.lz.manage.model.dto.fileInfo.FileInfoQuery;
import com.lz.manage.model.vo.fileInfo.FileInfoVo;
import com.lz.manage.service.IFileInfoService;
import com.lz.manage.service.IFolderInfoService;
import com.lz.manage.service.ITagInfoService;
import com.lz.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 文件信息Service业务层处理
 *
 * @author YY
 * @date 2025-07-17
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {
    @Resource
    private FileInfoMapper fileInfoMapper;
    @Resource
    private ISysUserService userService;
    @Resource
    private ITagInfoService tagInfoService;
    @Resource
    private IFolderInfoService folderInfoService;

    //region mybatis代码

    /**
     * 查询文件信息
     *
     * @param fileId 文件信息主键
     * @return 文件信息
     */
    @Override
    public FileInfo selectFileInfoByFileId(Long fileId) {
        return fileInfoMapper.selectFileInfoByFileId(fileId);
    }

    /**
     * 查询文件信息列表
     *
     * @param fileInfo 文件信息
     * @return 文件信息
     */
    @Override
    public List<FileInfo> selectFileInfoList(FileInfo fileInfo) {
        List<FileInfo> fileInfos = fileInfoMapper.selectFileInfoList(fileInfo);
        for (FileInfo info : fileInfos) {
            SysUser sysUser = userService.selectUserById(info.getUserId());
            if (StringUtils.isNotNull(sysUser) && StringUtils.isNotEmpty(sysUser.getUserName())) {
                info.setUserName(sysUser.getUserName());
            }
            if (StringUtils.isNotNull(info.getTagId())) {
                TagInfo tagInfo = tagInfoService.selectTagInfoByTagId(info.getTagId());
                if (StringUtils.isNotNull(tagInfo) && StringUtils.isNotEmpty(tagInfo.getTagName())) {
                    info.setTagName(tagInfo.getTagName());
                }
            }
            FolderInfo folderInfo = folderInfoService.selectFolderInfoByFolderId(info.getFolderId());
            if (StringUtils.isNotNull(folderInfo) && StringUtils.isNotEmpty(folderInfo.getFolderName())) {
                info.setFolderName(folderInfo.getFolderName());
            }
        }
        return fileInfos;
    }

    /**
     * 新增文件信息
     *
     * @param fileInfo 文件信息
     * @return 结果
     */
    @Override
    public int insertFileInfo(FileInfo fileInfo) {
        checkFileInfo(fileInfo);
        //获取文件后最
        String fileSuffix = FileUtils.getFileSuffix(fileInfo.getFileUrl());
        fileInfo.setFileSuffix(fileSuffix);
        fileInfo.setUserId(SecurityUtils.getUserId());
        fileInfo.setCreateTime(DateUtils.getNowDate());
        return fileInfoMapper.insertFileInfo(fileInfo);
    }

    private void checkFileInfo(FileInfo fileInfo) {
        if (StringUtils.isEmpty(fileInfo.getFileName())) {
            throw new RuntimeException("文件名不能为空");
        }
        if (StringUtils.isEmpty(fileInfo.getFileType())) {
            throw new RuntimeException("文件类型不能为空");
        }
        //判断文件夹是否存在
        FolderInfo folderInfo = folderInfoService.selectFolderInfoByFolderId(fileInfo.getFolderId());
        if (StringUtils.isNull(folderInfo)) {
            throw new RuntimeException("文件夹不存在");
        }
        //判断标签是否存在
        if (StringUtils.isNotNull(fileInfo.getTagId())) {
            TagInfo tagInfo = tagInfoService.selectTagInfoByTagId(fileInfo.getTagId());
            if (StringUtils.isNull(tagInfo)) {
                throw new RuntimeException("设置了标签但是标签不存在,标签不存在");
            }
        }
    }


    /**
     * 修改文件信息
     *
     * @param fileInfo 文件信息
     * @return 结果
     */
    @Override
    public int updateFileInfo(FileInfo fileInfo) {
        checkFileInfo(fileInfo);
        fileInfo.setUpdateTime(DateUtils.getNowDate());
        return fileInfoMapper.updateFileInfo(fileInfo);
    }

    /**
     * 批量删除文件信息
     *
     * @param fileIds 需要删除的文件信息主键
     * @return 结果
     */
    @Override
    public int deleteFileInfoByFileIds(Long[] fileIds) {
        //首先查询到对应文件，删除对应的文件
        List<FileInfo> list = this.list(new LambdaQueryWrapper<FileInfo>().in(FileInfo::getFileId, (Object[]) fileIds));
        for (FileInfo info : list) {
            FileUtils.deleteFileByLocalPath(info.getFileUrl());
        }
        return fileInfoMapper.deleteFileInfoByFileIds(fileIds);
    }

    /**
     * 删除文件信息信息
     *
     * @param fileId 文件信息主键
     * @return 结果
     */
    @Override
    public int deleteFileInfoByFileId(Long fileId) {
        return fileInfoMapper.deleteFileInfoByFileId(fileId);
    }

    //endregion
    @Override
    public QueryWrapper<FileInfo> getQueryWrapper(FileInfoQuery fileInfoQuery) {
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        //如果不使用params可以删除
        Map<String, Object> params = fileInfoQuery.getParams();
        if (StringUtils.isNull(params)) {
            params = new HashMap<>();
        }
        Long fileId = fileInfoQuery.getFileId();
        queryWrapper.eq(StringUtils.isNotNull(fileId), "file_id", fileId);

        Long folderId = fileInfoQuery.getFolderId();
        queryWrapper.eq(StringUtils.isNotNull(folderId), "folder_id", folderId);

        String fileName = fileInfoQuery.getFileName();
        queryWrapper.like(StringUtils.isNotEmpty(fileName), "file_name", fileName);

        String fileType = fileInfoQuery.getFileType();
        queryWrapper.eq(StringUtils.isNotEmpty(fileType), "file_type", fileType);

        String fileSuffix = fileInfoQuery.getFileSuffix();
        queryWrapper.eq(StringUtils.isNotEmpty(fileSuffix), "file_suffix", fileSuffix);

        Long tagId = fileInfoQuery.getTagId();
        queryWrapper.eq(StringUtils.isNotNull(tagId), "tag_id", tagId);

        Date createTime = fileInfoQuery.getCreateTime();
        queryWrapper.between(StringUtils.isNotNull(params.get("beginCreateTime")) && StringUtils.isNotNull(params.get("endCreateTime")), "create_time", params.get("beginCreateTime"), params.get("endCreateTime"));

        Date updateTime = fileInfoQuery.getUpdateTime();
        queryWrapper.between(StringUtils.isNotNull(params.get("beginUpdateTime")) && StringUtils.isNotNull(params.get("endUpdateTime")), "update_time", params.get("beginUpdateTime"), params.get("endUpdateTime"));

        return queryWrapper;
    }

    @Override
    public List<FileInfoVo> convertVoList(List<FileInfo> fileInfoList) {
        if (StringUtils.isEmpty(fileInfoList)) {
            return Collections.emptyList();
        }
        return fileInfoList.stream().map(FileInfoVo::objToVo).collect(Collectors.toList());
    }

}
